package com.czk.classreader.field;

import com.czk.utils.FileUtil;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;

import java.io.IOException;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/8/6 15:47
 */
public class ClassFieldAddCore {
    public static void main(String[] args) throws IOException {
       // String relative_path = "sample/Test.class";
        //String path = FileUtil.getFilePath(relative_path);
        String path = "F:\\IdeaProjects\\asm\\target\\classes\\com\\czk\\sample\\Test.class";
        byte[] bytes1 = FileUtil.readBytes(path);
        // read
        ClassReader cr = new ClassReader(bytes1);
        // write
        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
        // 串联classVisitor
        int api = Opcodes.ASM9;
        // 自己改变版本说的实现类
        ClassVisitor cv = new ClassAddFieldVisitor(api, cw, Opcodes.ACC_PUBLIC, "objectValue", "Ljava/lang/String;");
        int parsingOptions = ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES;
        // 连接
        cr.accept(cv, parsingOptions);
        // 字节
        byte[] bytes = cw.toByteArray();
        // 写出
        FileUtil.writeBytes(path, bytes);
    }
}
